//
//  LoggingClientInterceptor.swift
//  Center_RPC
//
//  Created by 蒋晨成 on 2021/12/29.
//

import Foundation
import GRPC
import LogMan
import NIO
import NIOHPACK

class LoggingClientInterceptor<Request, Response>: ClientInterceptor<Request, Response> {
    override func send(_ part: GRPCClientRequestPart<Request>, promise: EventLoopPromise<Void>?, context: ClientInterceptorContext<Request, Response>) {
        switch part {
        case .metadata(let headers):
            context.logger.debug("> Starting '\(context.path)' RPC, headers: '\(prettify(headers))'")
        case .message(let request, let metaData):
            context.logger.debug("> Starting '\(request)' , metaDataInfo : '\(metaData)'")
        case .end:
            context.logger.debug("> Ending '\(context.path)' RPC send")
        }
        context.send(part, promise: promise)
    }

    override func receive(_ part: GRPCClientResponsePart<Response>, context: ClientInterceptorContext<Request, Response>) {
        switch part {
        case .metadata(let headers):
            context.logger.debug("< Received headers: ''\(prettify(headers))")
        case .message(let response):
            context.logger.debug("< Received response: '\(response)'")
        case .end(let status, let trailers):
            context.logger.debug("< Response stream closed with status: '\(status)' and trailers: '\(prettify(trailers))'")
        }
        context.receive(part)
    }
}

extension LoggingClientInterceptor {
    func prettify(_ headers: HPACKHeaders) -> String {
        "[" + headers.map { name, value, _ in "'\(name)': '\(value)'" }
            .joined(separator: ", ") + "]"
    }
}
